<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑项目' : '新建项目'"
    width="900px"
    :before-close="handleClose"
    class="item-form-dialog"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入项目名称"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-input
                v-model="form.icon"
                placeholder="请输入图标名称或URL"
                maxlength="200"
              >
                <template #append>
                  <el-upload
                    :show-file-list="false"
                    :before-upload="handleUploadIcon"
                    accept="image/*"
                  >
                    <el-button>上传</el-button>
                  </el-upload>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入项目描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="内容类型" prop="content_type">
              <el-select v-model="form.content_type" placeholder="选择内容类型" style="width: 100%">
                <el-option label="页面" value="page" />
                <el-option label="API" value="api" />
                <el-option label="外部链接" value="external" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="显示顺序" prop="display_order">
              <el-input-number
                v-model="form.display_order"
                :min="0"
                :max="9999"
                placeholder="显示顺序"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- API端点和页面路径 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="API端点" prop="api_endpoint">
              <el-input
                v-model="form.api_endpoint"
                placeholder="请输入API端点"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="页面路径" prop="page_path">
              <el-input
                v-model="form.page_path"
                placeholder="请输入页面路径"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <!-- 内容配置 -->
      <div class="form-section">
        <h3>内容配置</h3>
        
        <!-- 页面类型项目配置 -->
        <div v-if="form.content_type === 'page'">
          <el-alert
            title="页面类型项目说明"
            type="info"
            :closable="false"
            style="margin-bottom: 20px"
          >
            页面类型项目通过页面路径访问，可以关联其他项目，也可以归属于分类。
          </el-alert>
        </div>
        
        <!-- API类型项目配置 -->
        <div v-else-if="form.content_type === 'api'">
          <el-alert
            title="API类型项目说明"
            type="info"
            :closable="false"
            style="margin-bottom: 20px"
          >
            API类型项目通过API端点提供服务，请确保API端点字段已正确填写。
          </el-alert>
        </div>
        
        <!-- 外部链接 -->
        <div v-else-if="form.content_type === 'external'">
          <el-form-item label="外部链接" prop="external_url">
            <el-input
              v-model="form.external_url"
              placeholder="请输入完整的URL地址"
              maxlength="500"
            >
              <template #prepend>URL</template>
            </el-input>
          </el-form-item>
        </div>
        
        <!-- 参数配置 -->
        <el-form-item label="参数配置" prop="params">
          <el-input
            v-model="form.params"
            type="textarea"
            :rows="4"
            placeholder="请输入JSON格式的参数"
          />
          <div class="form-tip">
            <el-text size="small" type="info">
              参数必须是有效的JSON格式
            </el-text>
          </div>
        </el-form-item>
      </div>
      
      <!-- 归属分类 -->
      <div class="form-section">
        <h3>归属分类</h3>
        
        <!-- 当前关联的分类 -->
        <div v-if="currentRelatedCategories.length > 0" class="current-relations">
          <h4>已关联分类:</h4>
          <div class="relation-list">
            <el-tag
              v-for="category in currentRelatedCategories"
              :key="category.id"
              closable
              @close="removeCategoryRelation(category.id)"
              class="relation-tag"
              type="success"
            >
              {{ category.name }}
            </el-tag>
          </div>
        </div>
        
        <!-- 添加分类关联 -->
        <div class="add-relation">
          <h4>添加分类关联:</h4>
          <el-row :gutter="10">
            <el-col :span="18">
              <el-select
                v-model="selectedCategoryId"
                placeholder="选择要关联的分类"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="category in availableCategories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button
                type="primary"
                @click="addCategoryRelation"
                :disabled="!selectedCategoryId"
                style="width: 100%"
              >
                添加关联
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <!-- 关联项目（仅页面类型项目显示） -->
      <div v-if="form.content_type === 'page'" class="form-section">
        <h3>关联项目</h3>
        
        <!-- 当前关联的项目 -->
        <div v-if="currentRelatedItems.length > 0" class="current-relations">
          <h4>已关联项目:</h4>
          <div class="relation-list">
            <el-tag
              v-for="item in currentRelatedItems"
              :key="item.id"
              closable
              @close="removeItemRelation(item.id)"
              class="relation-tag"
              type="warning"
            >
              {{ item.title || item.name }}
            </el-tag>
          </div>
        </div>
        
        <!-- 添加项目关联 -->
        <div class="add-relation">
          <h4>添加项目关联:</h4>
          <el-row :gutter="10">
            <el-col :span="18">
              <el-select
                v-model="selectedItemId"
                placeholder="选择要关联的项目"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="item in availableItems"
                  :key="item.id"
                  :label="item.title || item.name"
                  :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-button
                type="primary"
                @click="addItemRelation"
                :disabled="!selectedItemId"
                style="width: 100%"
              >
                添加关联
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  categories: {
    type: Array,
    default: () => []
  },
  pages: {
    type: Array,
    default: () => []
  },
  tempCategoryRelations: {
    type: Array,
    default: () => []
  },
  items: {
    type: Array,
    default: () => []
  },
  currentRelatedItems: {
    type: Array,
    default: () => []
  }
})

// Events
const emit = defineEmits([
  'update:visible', 
  'save', 
  'cancel',
  'add-category',
  'remove-category',
  'upload-image',
  'add-item-relation',
  'remove-item-relation',
  'rich-text-created'
])

// 响应式数据
const formRef = ref()
const saving = ref(false)
const selectedCategoryId = ref(null)
const selectedItemId = ref(null)
const form = ref({
  title: '',
  description: '',
  type: 'markdown',
  content: '',
  url: '',
  page_id: null,
  component_name: '',
  icon: '',
  params: '{}',
  status: 'active'
})

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 当前关联的分类
const currentRelatedCategories = computed(() => {
  if (!props.isEdit || !props.formData.id) return []
  return props.categories.filter(category => 
    category.items && category.items.some(item => item.id === props.formData.id)
  )
})

// 可用的分类（未关联的）
const availableCategories = computed(() => {
  if (!props.isEdit || !props.formData.id) return props.categories
  return props.categories.filter(category => 
    !category.items || !category.items.some(item => item.id === props.formData.id)
  )
})

// 可用的项目（排除当前项目和已关联的项目）
const availableItems = computed(() => {
  if (!props.items) return []
  
  const currentItemId = props.formData.id
  const relatedItemIds = props.currentRelatedItems.map(item => item.id)
  
  return props.items.filter(item => {
    // 排除当前项目本身
    if (currentItemId && item.id === currentItemId) return false
    // 排除已关联的项目
    if (relatedItemIds.includes(item.id)) return false
    // 排除其他页面类型的项目（页面类型项目不能关联其他页面类型项目）
    if (item.content_type === 'page' || item.type === 'page') return false
    return true
  })
})

// 表单验证规则
const rules = computed(() => {
  const baseRules = {
    title: [
      { required: true, message: '请输入项目标题', trigger: 'blur' },
      { min: 1, max: 100, message: '标题长度应在 1 到 100 个字符', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择内容类型', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择项目状态', trigger: 'change' }
    ],
    params: [
      { 
        validator: (rule, value, callback) => {
          if (value) {
            try {
              JSON.parse(value)
              callback()
            } catch (error) {
              callback(new Error('参数必须是有效的JSON格式'))
            }
          } else {
            callback()
          }
        }, 
        trigger: 'blur' 
      }
    ]
  }
  
  // 根据类型添加特定验证规则
  if (form.value.type === 'external') {
    baseRules.url = [
      { required: true, message: '请输入链接地址', trigger: 'blur' },
      { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
    ]
  } else if (form.value.type === 'page') {
    // 页面类型项目不需要验证page_id，但需要确保有分类关联
    // 分类关联的验证将在保存时进行
  } else if (form.value.type === 'component') {
    baseRules.component_name = [
      { required: true, message: '请输入组件名称', trigger: 'blur' },
      { min: 1, max: 100, message: '组件名称长度应在 1 到 100 个字符', trigger: 'blur' }
    ]
  }
  
  return baseRules
})

// 重置表单
const resetForm = () => {
  form.value = {
    title: '',
    description: '',
    type: 'markdown',
    content: '',
    url: '',
    page_id: null,
    component_name: '',
    icon: '',
    params: '{}',
    status: 'active'
  }
  selectedCategoryId.value = null
  selectedItemId.value = null
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData && Object.keys(newData).length > 0) {
      form.value = {
        title: newData.title || '',
        description: newData.description || '',
        type: newData.type || 'markdown',
        content: newData.content || '',
        url: newData.url || '',
        page_id: newData.page_id || null,
        component_name: newData.component_name || '',
        icon: newData.icon || '',
        params: newData.params || '{}',
        status: newData.status || 'active',
        ...newData
      }
    } else {
      resetForm()
    }
  },
  { immediate: true, deep: true }
)

// 监听类型变化，清空相关字段
watch(
  () => form.value.type,
  (newType, oldType) => {
    if (newType !== oldType) {
      // 清空其他类型的字段
      if (newType !== 'markdown') form.value.content = ''
      if (newType !== 'external') form.value.url = ''
      if (newType !== 'page') {
        form.value.page_id = null
      }
      if (newType !== 'component') form.value.component_name = ''
      
      // 清除验证错误
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
  }
)

// 添加分类关联
const addCategoryRelation = () => {
  if (selectedCategoryId.value) {
    emit('add-category', props.formData.id || 'new', selectedCategoryId.value)
    selectedCategoryId.value = null
  }
}

// 移除分类关联
const removeCategoryRelation = (categoryId) => {
  emit('remove-category', props.formData.id || 'new', categoryId)
}

// 添加项目关联
const addItemRelation = () => {
  if (selectedItemId.value) {
    emit('add-item-relation', props.formData.id || 'new', selectedItemId.value)
    selectedItemId.value = null
  }
}

// 移除项目关联
const removeItemRelation = (itemId) => {
  emit('remove-item-relation', props.formData.id || 'new', itemId)
}

// 处理图标上传
const handleUploadIcon = (file) => {
  emit('upload-image', file)
  return false // 阻止默认上传行为
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 页面类型项目不强制要求分类关联
    // 移除了强制分类关联的验证
    
    saving.value = true
    
    const formData = { ...form.value }
    
    // 确保 params 是有效的 JSON
    if (!formData.params || formData.params.trim() === '') {
      formData.params = '{}'
    }
    
    // 根据类型清理不需要的字段
    if (formData.type !== 'markdown') {
      delete formData.content
    }
    if (formData.type !== 'external') {
      delete formData.url
    }
    if (formData.type !== 'page') {
      delete formData.page_id
    }
    if (formData.type !== 'component') {
      delete formData.component_name
    }
    
    // 富文本类型需要设置默认的content_type和空内容
    if (formData.type === 'rich_text') {
      formData.content_type = 'rich_text'
      formData.content = '[]' // 空的富文本内容数组
    }
    
    // 如果是编辑模式，保留原有的 ID
    if (props.isEdit && props.formData.id) {
      formData.id = props.formData.id
    }
    
    emit('save', formData)
    
    ElMessage.success(props.isEdit ? '项目更新成功' : '项目创建成功')
    
    // 如果是富文本类型且不是编辑模式，发出特殊事件用于跳转到编辑器
    if (formData.type === 'rich_text' && !props.isEdit) {
      emit('rich-text-created', formData)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单填写是否正确')
  } finally {
    saving.value = false
  }
}

// 处理关闭
const handleClose = () => {
  emit('cancel')
  resetForm()
}
</script>

<style scoped>
.item-form-dialog :deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fafbfc;
}

.form-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.form-section h4 {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.form-tip {
  margin-top: 5px;
}

.current-relations {
  margin-bottom: 20px;
}

.relation-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.relation-tag {
  margin: 0;
}

.add-relation {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 100px;
}

:deep(.el-input-group__prepend) {
  background-color: #f5f7fa;
  color: #909399;
  border-color: #dcdfe6;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload .el-button) {
  width: 100%;
}
</style>